package clienteServidor.infoHWSWEquipo;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Memoria {
	private static final int KB= 1024,
							 MB= KB*KB;
	private static final String MEMORIA_LIBRE= "getFreePhysicalMemorySize",
							    MEMORIA_TOTAL= "getTotalPhysicalMemorySize";
	
	public static long getMemoriaLibre(){
		return obtenerValor(MEMORIA_LIBRE);
	}
	
	public static long getMemoriaTotal(){
		return obtenerValor(MEMORIA_TOTAL);
	}
	
	public static long getMemoriaLibreKB(){
		return obtenerValor(MEMORIA_LIBRE)/KB;
	}
	
	public static long getMemoriaTotalKB(){
		return obtenerValor(MEMORIA_TOTAL)/KB;
	}
	
	public static long getMemoriaLibreMB(){
		return obtenerValor(MEMORIA_LIBRE)/MB;
	}
	
	public static long getMemoriaTotalMB(){
		return obtenerValor(MEMORIA_TOTAL)/MB;
	}
	
	private static long obtenerValor(String nombreValor) {
		Object valor= null;
		OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();

		for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
			method.setAccessible(true);
			boolean condicion2= Modifier.isPublic(method.getModifiers()),
					condicion1= method.getName().startsWith(nombreValor);
			
			if (condicion1&&condicion2) {
				try {
					if(method.getName().startsWith(nombreValor)){
						valor= method.invoke(operatingSystemMXBean);
						break;
					}
				} catch (Exception e) {
					valor = 1;
				}
			}
		}
		return ((long)valor);
	}
	
	public static long getMemoriaOcupada(){
		return getMemoriaTotal()-getMemoriaLibre();
	}
	
	public static long getMemoriaOcupadaKB(){
		return getMemoriaTotalKB()-getMemoriaLibreKB();
	}
	
	public static long getMemoriaOcupadaMB(){
		return getMemoriaTotalMB()-getMemoriaLibreMB();
	}
	
	public static float getUsoMemoria(){
		return (float)getMemoriaOcupada()/getMemoriaTotal();
	}
	
	public static float getPorcentajeUsoMemoria(){
		return getUsoMemoria()*100.0f;
	}
	
	public static void main(String[] args) {
		System.out.println("Memoria Libre: "+Memoria.getMemoriaLibreMB());
		System.out.println("Memoria Ocupada: "+Memoria.getMemoriaOcupadaMB());
		System.out.println("Memoria Tolal: "+Memoria.getMemoriaTotalMB());
		System.out.println("Uso de Memoria: "+Memoria.getUsoMemoria());
		System.out.println("% Uso de Memoria: "+Memoria.getPorcentajeUsoMemoria());
	}
}
